package com.yuanfeng.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.RedisConstants;
import com.yuanfeng.commoms.dto.goods.CommunityArticleListDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.UUIDUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.CommunityArticleVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.CommunityArticleAddDTO;
import com.yuanfeng.goods.dto.CommunityContentReviewDTO;
import com.yuanfeng.goods.entity.GoodsArticleInfoEntity;
import com.yuanfeng.goods.mapper.*;
import com.yuanfeng.goods.service.GoodsArticleInfoService;
import com.yuanfeng.goods.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class GoodsArticleInfoServiceImpl extends ServiceImpl<GoodsArticleInfoMapper, GoodsArticleInfoEntity>
    implements GoodsArticleInfoService{

    @Autowired
    private GoodsArticleResourceMapper goodsArticleResourceMapper;
    @Autowired
    private GoodsArticleRemarkMapper goodsArticleRemarkMapper;
    @Autowired
    private GoodsArticleLikeMapper goodsArticleLikeMapper;
    @Autowired
    private GoodsArticleStarMapper goodsArticleStarMapper;
    @Autowired
    private GoodsArticleUserFollowMapper goodsArticleUserFollowMapper;

    @Override
    public ResponseResult updateCommunityAuditStatus(CommunityContentReviewDTO param) {
        this.baseMapper.updateCommunityAuditStatus(param);
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult selectContentList(Map<String, Object> map) {

        IPage<CommunityContentReviewVO> page=this.baseMapper.selectCommunityContentReview2(new Query<CommunityContentReviewVO>().getPage(map),
                map);
        for(CommunityContentReviewVO tmp : page.getRecords()){
            //查询心得 图片
            List<String> imageUrls = this.baseMapper.getImageReources(tmp.getArticleId());
            //查询心得视频
            String resourceUrl = this.baseMapper.getVideoReources(tmp.getArticleId());
            tmp.setImageUrl(imageUrls);
            tmp.setResourceUrl(resourceUrl);
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deleteArticle(Map<Object, Object> param) {
        this.baseMapper.deleteArticle(param);
        goodsArticleResourceMapper.deleteArticleResources(param);
        goodsArticleRemarkMapper.deleteRemarks(param);
        goodsArticleLikeMapper.deleteLikes(param);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getArticleDetails(Map<Object, Object> param) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.get("token").toString());
        if(null == ui){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        String userId = ui.getUserId();

        //更新阅读量
        this.baseMapper.updateReadNum(param);
        //获取心得基本信息
        String articleId = (String) param.get("articleId");
        param.put("remarkedId",articleId);
        Map<Object,Object> tmpMap = new HashMap<>();
        tmpMap.put("userId",userId);
        tmpMap.put("articleId",articleId);
        Integer starFlag = goodsArticleStarMapper.getStarFlag(tmpMap) > 0 ? 1 : 0;
        CommunityArticleDetailVO communityArticleDetail = this.baseMapper.queryArticleInfo(param);
        communityArticleDetail.setHasStarred(starFlag);
        if(null != communityArticleDetail.getUserId() && communityArticleDetail.getUserId().equals(userId)){
            communityArticleDetail.setIsMine(1);
            communityArticleDetail.setIsFollowed(null);
        }else{
            communityArticleDetail.setIsMine(0);
            Integer followFlag = goodsArticleUserFollowMapper.getFollowerFlag(communityArticleDetail.getUserId(),userId);
            if(followFlag >0 ){
                communityArticleDetail.setIsFollowed(1);
            }else{
                communityArticleDetail.setIsFollowed(0);
            }
        }
        param.put("userId",userId);
        param.put("likedId",articleId);
        param.put("likeType",1);
        Integer likeId = goodsArticleLikeMapper.getArticleIsLiked(param);
        if(null != likeId && likeId >0 ) {
            communityArticleDetail.setArticleIsLiked(1);
            communityArticleDetail.setLikeId(likeId);
        }else{
            communityArticleDetail.setArticleIsLiked(0);
            communityArticleDetail.setLikeId(null);
        }
        //获取作者基本信息
        Map<String,String> userInfo = this.baseMapper.getUserInfo(communityArticleDetail.getUserId());
        if(null!=userInfo) {
            communityArticleDetail.setUserName(userInfo.get("userName"));
            communityArticleDetail.setUserAvatar(userInfo.get("userAvatar"));
            //获取心得媒体资源
        }
        //查询心得 图片
        List<String> imageUrls = goodsArticleResourceMapper.getImageReources(param.get("articleId").toString());
        communityArticleDetail.setImageUrls(imageUrls);
        //查询心得视频
        String resourceUrl = goodsArticleResourceMapper.getVideoReources(param.get("articleId").toString());
        communityArticleDetail.setResourceUrl(resourceUrl);
        //获取一级评论信息
        param.put("remarkType",1);
        List<CommunityArticleRemarkEntityVO> mainRemarks = goodsArticleRemarkMapper.queryRemarks(param);
        if(null != mainRemarks && !mainRemarks.isEmpty()) {
            getUserInfo(mainRemarks, userId);
            for (CommunityArticleRemarkEntityVO mainRemark : mainRemarks) {
                //获取二级评论信息
                param.put("remarkedId", mainRemark.getRemarkId());
                param.put("remarkType", 2);
                param.put("userId",userId);
                Integer likeIdForRemark = goodsArticleLikeMapper.getRemarkisLiked(param);
                if(null != likeIdForRemark && likeIdForRemark>0){
                    mainRemark.setIsLiked(1);
                    mainRemark.setLikeId(likeIdForRemark);
                }else{
                    mainRemark.setIsLiked(0);
                    mainRemark.setLikeId(null);
                }
                List<CommunityArticleRemarkEntityVO> subRemarks = goodsArticleRemarkMapper.queryRemarks(param);
                for(CommunityArticleRemarkEntityVO subRemark : subRemarks){
                    param.put("remarkedId", subRemark.getRemarkId());
                    param.put("remarkType", 2);
                    param.put("userId",userId);
                    Integer likeIdForSRemark = goodsArticleLikeMapper.getRemarkisLiked(param);
                    if(null != likeIdForSRemark && likeIdForSRemark>0){
                        subRemark.setIsLiked(1);
                        subRemark.setLikeId(likeIdForSRemark);
                    }else{
                        subRemark.setIsLiked(0);
                        subRemark.setLikeId(null);
                    }
                }
                getUserInfo(subRemarks, userId);
                mainRemark.setRemarkList(subRemarks);
            }
        }
        if (CollectionUtils.isEmpty(mainRemarks)) {
            mainRemarks = Lists.newArrayList();
        }
        communityArticleDetail.setMainRemarks(mainRemarks);
        return ResponseResult.success(communityArticleDetail);
    }
    private void getUserInfo(List<CommunityArticleRemarkEntityVO> mainRemarks,String userId) {
        for(CommunityArticleRemarkEntityVO mainRemark:mainRemarks){
            Map<String,String> remarkUserInfo = this.baseMapper.getUserInfo(mainRemark.getRemarkUser());
            if(null!=remarkUserInfo){
                mainRemark.setRemarkUserName(remarkUserInfo.get("userName"));
                mainRemark.setRemarkUserAvatar(remarkUserInfo.get("userAvatar"));
            }
            Map<String,String> remarkedUserInfo = this.baseMapper.getUserInfo(mainRemark.getRemarkedUser());
            if(null!=remarkedUserInfo){
                mainRemark.setRemarkedUserName(remarkedUserInfo.get("userName"));
                mainRemark.setRemarkedUserAvatar(remarkedUserInfo.get("userAvatar"));
            }
            if(userId.equals(mainRemark.getRemarkUser())){
                mainRemark.setOwnRemark(1);
            }else{
                mainRemark.setOwnRemark(0);
            }
        }
    }

    @Override
    public ResponseResult queryUserInfo(Map<Object, Object> param) {
        //若查看他人心得列表，则需要传入UserId;
        //若查看自己的心得列表，则需要传入token;
        if(param.get("userId") == null) {
            UserInfoVO ui = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.get("token").toString());
            if (null != ui) {
                param.put("userId",ui.getUserId());
            }
        }
        CommunityUserInfoVO userInfo = this.baseMapper.getUserInfoEntity(param);
        Integer likedNum = goodsArticleLikeMapper.getLikedNum(param);
        userInfo.setLikedNum(likedNum);
        Integer followNum = goodsArticleUserFollowMapper.getFollowNum(param);
        userInfo.setFollowNum(followNum);
        Integer followedNum = goodsArticleUserFollowMapper.getFollowedNum(param);
        userInfo.setFollowedNum(followedNum);
        Integer starNum = goodsArticleStarMapper.getStarNum(param);
        userInfo.setStarNum(starNum);
        if(null != userInfo && null == userInfo.getUserSignature()){
            userInfo.setUserSignature("还来不及增加介绍呢！");
        }
        return ResponseResult.success(userInfo);
    }

    @Override
    public ResponseResult searchUserList(Map<Object, Object> param) {
        List<CommunityUserInfoVO> resultList = new ArrayList<>();
        String token = (String) param.get("token");
        String userId = "";
        Integer currentPage = (Integer) param.get("page");
        Integer pageSize =  (Integer) param.get("limit");
        boolean loginFlag = false;
        //置空全查已关注用户
        param.put("currentPage",null);
        param.put("pageSize",null);
        //关注用户id列表
        List<String> followUserIds = new ArrayList<>();
        List<String> resultAllUserIds = new ArrayList<>();
        List<String> resultAllUserIdsTmp = new ArrayList<>();
        List<String> hasArticleUserIds = new ArrayList<>();
        List<String> allUserIds = null;
        //全部用户id列表
        allUserIds = this.baseMapper.getAllUserIds(param);
        //发表过心得且审核通过的用户id列表
        hasArticleUserIds = this.baseMapper.getHasArticleUserIds(param);
        allUserIds.removeAll(hasArticleUserIds);
        //resultAllUserIdsTmp所有用户列表,优先展示发表过心得的用户
        resultAllUserIdsTmp.addAll(hasArticleUserIds);
        resultAllUserIdsTmp.addAll(allUserIds);
        resultAllUserIds.addAll(resultAllUserIdsTmp);
        //token不为空则为用户登录状态,首先展示发表过心得用户，最后是未发表过心得的用户
        if (null != token && !"".equals(token)) {
            boolean isExist = RedisUtil.exists(RedisConstants.FKGOU_USER_TOKEN_USER + token);
            if (!isExist){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
            }
            userId = RedisUtil.get(RedisConstants.FKGOU_USER_TOKEN_USERID + token);
            param.put("userId",userId);
            loginFlag = true;
            resultAllUserIdsTmp.clear();
            if(null != userId ) {
                if(resultAllUserIds.contains(userId)) {
                    resultAllUserIdsTmp.add(userId);
                    resultAllUserIds.removeAll(resultAllUserIdsTmp);
                }
            }
            followUserIds = goodsArticleUserFollowMapper.getFollowUserIds2(param);
            //token为空则为用户未登录
        }else{
            resultAllUserIds = resultAllUserIdsTmp;
        }

        List<String> pagedResultAllUserIds = Lists.newArrayList();
        if (CollectionUtils.isEmpty(resultAllUserIds)) {
            pagedResultAllUserIds = Lists.newArrayList();
        }
        int totalCount = resultAllUserIds.size();
        if(totalCount > 0) {
            int fromIndex = (currentPage-1) * pageSize;
            int toIndex = currentPage * pageSize;
            if (toIndex > totalCount) {
                toIndex = totalCount;
            }
            pagedResultAllUserIds = resultAllUserIds.subList(fromIndex, toIndex);
        }


        //根据用户id查询对应的用户数据及心得数据进行封装
        for(int i=0; i < pagedResultAllUserIds.size(); i++){
            CommunityUserInfoVO userInfo = new CommunityUserInfoVO();
            String uid = pagedResultAllUserIds.get(i);
            Map<String,String> tmpMap= this.baseMapper.getUserInfo(uid);
            userInfo.setUserId(uid);
            userInfo.setUserName(tmpMap.get("userName"));
            userInfo.setUserAvatar(tmpMap.get("userAvatar"));
            Map<Object,Object> queryMap = new HashMap<>();
            queryMap.put("userId",uid);
            Integer likedNum = goodsArticleLikeMapper.getLikedNum(queryMap);
            Integer articleNum = this.baseMapper.getArticleNum(queryMap);
            if(articleNum > 3){
                articleNum = 3;
            }
            userInfo.setLikedNum(likedNum);
            userInfo.setArticleNum(articleNum);
            //若已登录则查询是否关注该用户
            if(loginFlag){
                if(followUserIds.contains(uid)){
                    userInfo.setIsFollowed(1);
                }else{
                    userInfo.setIsFollowed(0);
                }
                //若未登录则都显示未关注
            }else{
                userInfo.setIsFollowed(0);
            }
            List<CommunityArticleSmallEntityVO> articles = this.baseMapper.getArticleSmallEntity(uid);
            if(null == articles || articles.isEmpty()){
                articles = new ArrayList<>();
            }
            userInfo.setArticleList(articles);
            resultList.add(userInfo);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("resultList",resultList);
        map.put("totalCount",totalCount);
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult queryGoods(Map<Object, Object> param) {
        Integer currentPage = (Integer) param.get("page");
        Integer pageSize = (Integer) param.get("limit");
        Map<String,Object> resultMap = new HashMap<>();
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if (null == ui) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }else{
            param.put("userId", ui.getUserId());
            List<String> orderIds = this.baseMapper.queryOrder(param);
            List<GoodsDetailVO> allGoodsList = new ArrayList<>();
            for(String orderId : orderIds){
                List<GoodsDetailVO> goodsDetails = this.baseMapper.queryGoods(orderId);
                allGoodsList.addAll(goodsDetails);
            }
            List<GoodsDetailVO> allDistinctGoodsList = allGoodsList.stream().distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(allDistinctGoodsList)) {
                allDistinctGoodsList = Lists.newArrayList();
            }
            Integer totalCount = allDistinctGoodsList.size();
            resultMap.put("totalCount",totalCount);
            List<GoodsDetailVO> pageList = Lists.newArrayList();;
            if(!allDistinctGoodsList.isEmpty()) {
                int fromIndex = (currentPage-1) * pageSize;
                int toIndex = currentPage * pageSize;
                if (toIndex > totalCount) {
                    toIndex = totalCount;
                }
                pageList = allDistinctGoodsList.subList(fromIndex, toIndex);
            }
            resultMap.put("goodsList",pageList);
        }
        return ResponseResult.success(resultMap);
    }

    @Override
    public ResponseResult addArticle(CommunityArticleAddDTO param) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == ui) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }else{
            param.setUserId(ui.getUserId());
        }
        String uuid = UUIDUtil.getUUID();
        param.setArticleId(uuid);
        //图片心得
        if (param.getImageUrl() != null && param.getImageUrl().size() > 0) {
            param.setResourceType(1);
            param.setArticleType(1);
            //视频心得
        }else {
            param.setResourceType(2);
            param.setArticleType(2);
        }
        this.baseMapper.addArticleInfo(param);
        //图片心得
        if(1 == param.getResourceType()){
            if(null != param.getResourceUrl()){
                param.setResourceType(2);
                goodsArticleResourceMapper.addArticleResources(param);
            }
            for(String imageUrl : param.getImageUrl()){
                param.setResourceUrl(imageUrl);
                param.setResourceType(1);
                goodsArticleResourceMapper.addArticleResources(param);
            }
            //视频心得
        }else{
            goodsArticleResourceMapper.addArticleResources(param);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult getArticleList(CommunityArticleListDTO param) {
        //若查看他人心得列表，则需要传入UserId;
        //若查看自己的心得列表，则需要传入token;
        //查看首页全部的心得列表，则不需要传入UserId和token
        if((param.getUserId() == null || param.getUserId().isEmpty()) && param.getToken() != null && !param.getToken().isEmpty()) {
            UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(param.getToken());
            if (ui == null) {
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
            } else {
                param.setUserId(ui.getUserId());
            }
        }
        Page<CommunityArticleVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<CommunityArticleVO> result = this.baseMapper.getArticleList(page, param);
        //查询是否有数据
        if (!CollectionUtils.isEmpty(result.getRecords())) {
            for (CommunityArticleVO communityArticleResult : result.getRecords()) {
                Map<String, String> userInfo = this.baseMapper.getUserInfo(communityArticleResult.getUserId());
                communityArticleResult.setUserName(userInfo.get("userName"));
                communityArticleResult.setUserAvatar(userInfo.get("userAvatar"));
            }
        }
        return ResponseResult.success(PageUtils.getPage(result));
    }

    @Override
    public ResponseResult queryCommunityTopics() {
        List<CommunityArticleTagClassVO> params = this.baseMapper.queryGoodsCats();
        return ResponseResult.success(params);
    }

    @Override
    public ResponseResult queryRandomInvitation(Map<Object, Object> param) {
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + param.get("token").toString());
        List<CommunityArticleVO> communityArticleResultsList = this.baseMapper.queryRandomInvitation(userId);
        for (CommunityArticleVO communityArticleResult : communityArticleResultsList) {
            //获取用户头像 名称
            Map<String, String> userInfo = this.baseMapper.getUserInfo(communityArticleResult.getUserId());
            communityArticleResult.setUserName(userInfo.get("userName"));
            communityArticleResult.setUserAvatar(userInfo.get("userAvatar"));
            //1 关注 0 未关注
            communityArticleResult.setHasFollowed(0);
            Map<Object, Object> tmMap = new HashMap<>();
            tmMap.put("userId", communityArticleResult.getUserId());
            //获取关注数
            Integer followerNum = this.baseMapper.getFollowedNum(tmMap);
            communityArticleResult.setFollowerNum(followerNum);
        }
        return ResponseResult.success(communityArticleResultsList);
    }

    @Override
    public ResponseResult getFollowArticleList(CommunityArticleListDTO param) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        Map<Object, Object> tmpMap = new HashMap<>();
        tmpMap.put("userId", ui.getUserId());
        List<String> followUserIds = this.baseMapper.getFollowUserIds(tmpMap);
        if (null == followUserIds || followUserIds.isEmpty()) {
            followUserIds = new ArrayList<>();
        }
        param.setFollowUserIds(followUserIds);
        Page<CommunityArticleVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<CommunityArticleVO> result = this.baseMapper.getFollowArticleList(page, param);
        //查询是否有数据
        if (CollectionUtils.isEmpty(result.getRecords())) {
            return ResponseResult.success(BizCodeEnume.COLLECTION_IS_EMPTY);
        }
        for (CommunityArticleVO communityArticleResult : result.getRecords()) {
            Map<String, String> userInfo = this.baseMapper.getUserInfo(communityArticleResult.getUserId());
            communityArticleResult.setUserName(userInfo.get("userName"));
            communityArticleResult.setUserAvatar(userInfo.get("userAvatar"));
            communityArticleResult.setHasFollowed(1);
            Map<Object, Object> tmMap = new HashMap<>();
            tmMap.put("userId", communityArticleResult.getUserId());
            Integer followerNum = this.baseMapper.getFollowedNum(tmMap);
            communityArticleResult.setFollowerNum(followerNum);
        }
        return ResponseResult.success(PageUtils.getPage(result));
    }
}




